<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Promise</title>
</head>
<body>
<script>
    // const promise = new Promise(function(resolve,reject){
    //     resolve('success')
    // })
    // promise.then(res=>{
    //     console.log(res) // success
    //     return 'ok'
    // }).then(res=>{
    //     console.log(res) // ok
    // })
    class Promise{
        callbacks = []
        state = 'pending' // 保存状态
        value = null // 保存结果
        constructor(fn) {
            fn(this._resolve.bind(this))
        }
        then(onFulfilled){
            if(this.state === 'pending'){ // 如果还没改变状态，将回调添加到回调函数中，
                this.callbacks.push(onFulfilled)
            }else{ // 如果状态改变，那就直接执行当前回调
                onFulfilled(this.value);
            }
            return this
        }
        _resolve(value){
            this.state = 'fulfilled'
            this.value = value
            this.callbacks.forEach(fn1=>fn1(value))
        }
    }

    let p = new Promise(resolve=>{
        console.log('同步执行')
        setTimeout(()=>{
            resolve('5s')
        },5000)

    })
    p.then(res=>{
        console.log('then1',res)
        return '123'
    }).then(res=>{
        console.log('then2',res)
    })

    setTimeout(() => {
        p.then(tip => {
            console.log('then3', tip);
        })
    });

</script>
</body>
</html>